# coding:utf8
__author__ = 'golker'

from flask_login import current_user
import datetime
from flask import g, request
from .extensions import db, mymail
import models
from _main import forms


def config_request_handles(app):
    # 每次请求之前
    @app.before_request
    def before_request():
        g.search_form = forms.SearchForm()
        g.user = current_user
        if g.user.is_authenticated():
            g.user.last_seen = datetime.datetime.now()
            db.session.add(g.user)
            db.session.commit()
        if request.url.find('static') < 0 and request.url.find('favicon.ico') < 0:
            agent = request.headers['User-Agent']
            url = request.base_url
            log = models.Visit_log(timestamp=datetime.datetime.now(),
                                   ip=request.remote_addr,
                                   url=url,
                                   agent=agent)
            db.session.add(log)
            db.session.commit()

    # 第一次访问从数据库中加载设置
    @app.before_first_request
    def somesetfromdb():
        from golsee import models

        server = str(models.Settings.query.filter_by(type='MAIL_SERVER').first().value)
        port = int(models.Settings.query.filter_by(type='MAIL_PORT').first().value)
        tls = eval(models.Settings.query.filter_by(type='MAIL_USE_TLS').first().value)
        ssl = eval(models.Settings.query.filter_by(type='MAIL_USE_SSL').first().value)
        username = str(models.Settings.query.filter_by(type='MAIL_USERNAME').first().value)
        password = str(models.Settings.query.filter_by(type='MAIL_PASSWORD').first().value)
        admin = str(models.Settings.query.filter_by(type='ADMIN').first().value)
        dtheme = str(models.Settings.query.filter_by(type='DEFAULT_THEME').first().value)
        app.config.update(MAIL_SERVER=server,
                          MAIL_PORT=port,
                          MAIL_USE_TLS=tls,
                          MAIL_USE_SSL=ssl,
                          MAIL_USERNAME=username,
                          MAIL_PASSWORD=password,
                          ADMIN_EMAIL=admin,
                          DEFAULT_THEME=dtheme)
        mymail.init_app(app)
